Chapter 1: Variables

-- A Python Course for the Humanities by Folgert Karsdorp and Maarten van Gompel, with modifications by Mike Kestemont and Lars Wieneke


First steps

Everyone can learn how to program and the best way to learn it is by doing it. This tutorial on the Python programming language for people from the Humanities is extremely hands-on: you will have to write a lot of programming code yourself from the very beginning onwards. For writing the Python code in this tutorial, you can use the many 'code blocks' you will encounter, such as the grey block immediately below. Place your cursor inside this block and press ctrl+enter to "run" or execute the code. Let's begin right away: run your first little program!


In [ ]:
print("Mike")
  • Can you describe what this code did?
  • Can you adapt the code in this box yourself and make it print your own name?

Apart from printing words to your screen, you can also use Python to do calculations.

  • Use the code block below to calculate how many minutes there are in seven weeks? (Hint: multiplication is done using the * symbol in Python.)

In [ ]:
# insert your own code here!

Excellent! You have just written and executed your very first program! Please make sure to run every single one of the following code blocks in the same manner - otherwise a lot of the examples won't properly work.

So far, we used only Python as a pretty minimalistic calculator, but there is more to discover.

Variables and values

Imagine that we want to store the number we just calculated so we can use it later. To do this we need to 'assign' a name to a value using the = symbol.


In [ ]:
x = 5
print(x)

If you vaguely remember your math-classes in school, this should look familiar. It is basically the same notation with the name of the variable on the left, the value on the right, and the = sign in the middle.

In the code block above, two things happen. First, we fill x with a value, in our case 2. This variable x behaves pretty much like a box on which we write an x with a thick, black marker to find it back later. We then print the contents of this box, using the print() command.

  • Now copy the outcome of your code calculating the number of minutes in seven weeks and assign this number to x. Run the code again.

The box metaphor for a variable goes a long way: in such a box you can put whatever value you want, e.g. the number of minutes in seven weeks. When you re-assign a variable, you remove the content of the box and put something new in it. In Python, the term 'variable' refers to such a box, whereas the term 'value' refers to what is inside this box.

When we have stored values inside variables, we can do interesting things with these variables. You can, for instance, run the calculations in the block below to see the effect of the following five lines of code. Symbols like =, +, - and * are called 'operators' in programming: they all provide a very basic functionality such as assigning values to variables or doing multiplication and subtraction.


In [ ]:
x = 2
print(x)
print(x * x)
print(x + x)
print(x - 6)

So far, we have only used a variable called x. Nevertheless, we are entirely free to change the names of our variables, as long as these names do not contain strange characters, such as spaces, numbers or punctuation marks. (Underscores, however, are allowed inside names!) In the following block, we assign the outcome of our calculation to a variable that has a more meaningful name than the abstract name x.


In [ ]:
seconds_in_seven_weeks = 70560
print(seconds_in_seven_weeks)

In Python we can also copy the contents of a variable into another variable, which is what happens in the block below. You should of course watch out in such cases: make sure that you keep track of the value of each individual variable in your code. Each variable will always contain the value that you last assigned to it:


In [ ]:
first_number = 5
second_number = first_number
first_number = 3
print(first_number)
print(second_number)

Remember: as with boxes in real life, it is always a good idea to give the box a clear, yet short name, with your black marker - the name should accurately reflect what is inside the box. Just like you don't write cookies on a box that in reality contains bananas, it is important to always give your Python variables a sensible name. In the code block below, for instance, we make the stupid mistake of calling a variable months, while it actually contains seconds...


In [ ]:
# not recommended...
months = 70560
print(months)

Variables are also case sensitive, accessing months is not the same as Months


In [ ]:
print(months)

In [ ]:
print(Months)

So far we have only assigned numbers such as 2 or 70560 to our variables. Such whole numbers are called 'integers' in programming, because they don't have anymore digits 'after the dot'. Numbers that do have digits after the dot (e.g. 67.278 or 191.200), are called 'floating-point numbers' in programming or simply 'floats'. Note that Python uses dots in floats, whereas some European languages use a comma here. Both integers and floats can be positive numbers (e.g. 70 or 4.36) as well as negative numbers (e.g. -70 or 4.36). You can just as easily assign floats to variables:


In [ ]:
some_float = 23.987
print(some_float)
some_float = -4.56
print(some_float)

On the whole, the difference between integers and floats is of course important for divisions where you often end up with floats:


In [ ]:
x = 5/2
print(x)

You will undoubtedly remember from your math classes in high school that there is something called 'operator precedence', meaning that multiplication, for instance, will always be executed before subtraction. In Python you can explicitly set the order in which arithmetic operations are executed, using round brackets. Compare the following lines of code:


In [ ]:
nr1 = 10-2/4
nr2 = (10-2)/4
nr3 = 10-(2/4)
print(nr1)
print(nr2)
print(nr3)

Using the operators we have learned about above, we can change the variables in our code as many times as we want. We can assign new values to old variables, just like we can put new or more things in the boxes which we already had. Say, for instance, that yesterday we counted how many books we have in our office and that we stored this count in our code as follows:


In [ ]:
number_of_books = 100

Suppose that we buy a new book for the office today: we can now update our book count accordingly, by adding one to our previous count:


In [ ]:
number_of_books = number_of_books + 1
print(number_of_books)

Updates like these happen a lot. Python therefore provides a shortcut and you can write the same thing using +=.


In [ ]:
number_of_books += 5
print(number_of_books)

This special shortcut (+=) is called an operator too. Apart from multiplication (+=), the operator has variants for subtraction (-=), multiplication (*=) and division (/=) too:


In [ ]:
number_of_books -= 5
print(number_of_books)
number_of_books *= 2
print(number_of_books)
number_of_books /= 2
print(number_of_books)

What we have learnt

To finish this section, here is an overview of the concepts you have learnt. Go through the list and make sure you understand all the concepts.

  • variable
  • value
  • assignment operator (=)
  • difference between variables and values
  • integers vs. floats
  • operators for multiplication (*), subtraction (-), addition (+), division (/)
  • the shortcut operators: +=, -=, *=, /=
  • print()

Text strings

So far, we have only worked with variables that contain numbers (integers like -5 or 72 or floats like 45.89 or -5.609). Note, however, that variables can also contain other things than numbers. Many disciplines within the humanities work on texts. Quite naturally, programming skills for the humanities will have to focus a lot on manipulating texts. Have a look at the code block below, for instance. Here we put text, namely the title of a book, as a value inside the variable book. Then, we print what is inside the book variable.


In [ ]:
book = "The Lord of the Flies"
print(book)

Such a piece of text ("The Lord of the Flies") is called a 'string' in Python (cf. a string of characters). Strings in Python must always be enclosed with 'quotes' (either single or double quotes). Without those quotes, Python will think it's dealing with the name of some variable that has been defined earlier, because variable names never take quotes. The following distinction is confusing, but extremely important: variable names (without quotes) and string values (with quotes) look similar, but they serve a completely different purpose. Compare:


In [ ]:
name = "Bonny"
Bonny = "name"
Clyde = "Clyde"
print(name)
print (Bonny)
print(Clyde)

Some of the arithmetic operators we saw earlier can also be used to do useful things with strings. Both the multiplication operator (*) and the addition operator (+) provide interesting functionality for dealing with strings, as the block below illustrates.


In [ ]:
original_string = "bla"
new_string = 2*original_string
print(new_string)
new_string = new_string+"h"
print(new_string)

Adding strings together is called 'string concatenation' or simply 'concatenation' in programming. Use the block below to find out whether you could can also use the shortcut += operator for adding an 'h' to the variable original_string. Don't forget to check the result by printing it!


In [ ]:
original_string = "blabla"
# add an 'h'...
print(original_string)

We now would like you to write some code that defines a variable, name, and assign to it a string that is your name. If your first name is shorter than 5 characters, use your last name. If your last name is also shorter than 5 characters, use the combination of your first and last name. Now print the variable containing your name to the screen.


In [ ]:
# your name code goes here...

Strings are called strings because they consist of a series (or 'string') of individual characters. We can access these individual characters in Python with the help of 'indexing', because each character in a string has a unique 'index'. To print the first letter of your name, you can type:


In [ ]:
first_letter = name[0]
print(first_letter)

Take a look at the string "Mr White". We use the index 0 to access the first character in the string. This might seem odd, but remember that all indexes in Python start at zero. Whenever you count in Python, you start at 0 instead of 1. Note that the space character gets an index too, namely 2. This is something you will have to get used to!

Because you know the length of your name you can ask for the last letter of your name:


In [ ]:
last_letter = name[# fill in the last index of your name (tip indexes start at 0)]
print(last_letter)

It is rather inconvenient having to know how long our strings are if we want to find out what its last letter is. Python provides a simple way of accessing a string 'from the rear':


In [ ]:
last_letter = name[-1]
print(last_letter)

To access the last character in a string you have to use the index [-1]. Alternatively, there is the len() command which returns the length of a string:


In [ ]:
print(len(name))

Do you understand the following code block? Can you explain what is happening?


In [ ]:
print(name[len(name)-1])

Now can you write some code that defines a variable but_last_letter and assigns to this variable the one but last letter of your name?


In [ ]:
but_last_letter = name[# insert your code here]
print(but_last_letter)

You're starting to become a real expert in indexing strings. Now what if we would like to find out what the last two or three letters of our name are? In Python we can use so-called 'slice-indexes' or 'slices' for short. To find the first two letters of our name we type in:


In [ ]:
first_two_letters = name[0:2]
print(first_two_letters)

The 0 index is optional, so we could just as well type in name[:2]. This says: take all characters of name until you reach index 2 (i.e. up to the third letter, but not including the third letter). We can also start at index 2 and leave the end index unspecified:


In [ ]:
without_first_two_letters = name[2:]
print(without_first_two_letters)

Because we did not specify the end index, Python continues until it reaches the end of our string. If we would like to find out what the last two letters of our name are, we can type in:


In [ ]:
last_two_letters = name[-2:]
print(last_two_letters)

DIY

  • Can you define a variable middle_letters and assign to it all letters of your name except for the first two and the last two?

In [ ]:
# insert your middle_letters code here
  • Given the following two words, can you write code that prints out the word humanities using only slicing and concatenation? (So, no quotes are allowed in your code.) Can you print out how many characters the word humanities counts?

In [ ]:
word1 = "human"
word2 = "opportunities"

"Casting" variables

Above, we have already learned that each variable as a data type: variables can be strings, floats, integers, etc. Sometimes it is necessary to convert one type into the other. Consider this:


In [ ]:
x = "5"
y = 2
print(x + y)

This should raise an error on your machine: does the error message gives you a hint as to why this doesn't work? x is a string, and y is an integer. Because of this, you cannot sum them. Luckily there exist ways to 'cast' variables from one type of variable into another type of variable.

  • Do you understand the outcome of the following code?
  • Can you comment in your own words on the effect of applying int() and str() to variables?

In [ ]:
x = "5"
y = 2
print(x + str(y))
print(int(x) + y)

Other types of conversions are possible as well, and we will see a couple of them in the next chapters. Because variables can change data type anytime they want, we say that Python uses 'dynamic typing', as opposed to other more 'strict' languages that use 'strong typing'. You can check a variable's type using the type()command.

DIY

When you exchange code with fellow programmers (as you will often have to do in the real world), it is really helpful if you include some useful information about your scripts. Have a look at the code block below and read about commenting on Python code in the comments:


In [ ]:
# comment: insert your code here.
# BTW: Have you noticed that everything behind the hashtag 
print("Something...") # on a line is ignored by your python interpreter?
print("and something else..") # this is really helpful to comment on your code!
"""Another way
of commenting on your code is via 
triple quotes -- these can be distributed over multiple """ # lines
print("Done.")

So, how many ways are there to comment on your code in Python?


What we have learnt

To finish this section, here is an overview of what we have learnt. Go through the list and make sure you understand all the concepts.

  • concatenation
  • index
  • slicing
  • zero-indexed numbering
  • len()
  • type casting: int() and str()
  • type()
  • code commenting via hashtags and triple double quotes

Final Exercises Chapter 1

Inspired by Think Python by Allen B. Downey (http://thinkpython.com), Introduction to Programming Using Python by Y. Liang (Pearson, 2013). Some exercises below have been taken from: http://www.ling.gu.se/~lager/python_exercises.html.

  • Ex. 1: Suppose the cover price of a book is 24.95 EUR, but bookstores get a 40 percent discount. Shipping costs 3 EUR for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies? Print the result in a pretty fashion, using casting where necessary!

In [ ]:
# your code goes here
  • Ex. 2: Can you identify and explain the errors in the following lines of code? Correct them please!

In [ ]:
print("A message").
print("A message')
print('A messagef"')
  • Ex. 3: When something is wrong with your code, Python will raise errors. Often these will be 'syntax errors' that signal that something is wrong with the form of your code (i.e. a SyntaxError like the one thrown in the previous exercice). There are also 'runtime errors' that signal that your code was in itself formally correct, but that something went wrong during the code's execution. A good example is the ZeroDivisionError. Try to make Python throw such a ZeroDivisionError!

In [ ]:
# ZeroDivisionError
  • Ex. 4: Write a program that assigns the result of 9.5 * 4.5 - 2.5 * 345.5 - 3.5 to a variable. Print this variable. Use round brackets to indicate 'operator precedence' and make sure that subtractions are performed before multiplications. When you convert the outcome to a string, how many characters does it count?

In [ ]:
# insert your code here
  • Ex. 5: Define the variables a=2, b=20007 and c=5. Using only the operations you learned about above, can you now print the following numbers: 2005, 252525252, 2510, -60025 and 2002507? (Hint: use type casting and string slicing to access parts of the original numbers!)

In [ ]:
# numbers
  • Ex. 6: Define three variables var1, var2 and var3. Calculate the average of these variables and assign it to average. Print the result in a fancy manner. Add three comments to this piece of code using three different ways.

In [ ]:
# average
  • Ex. 7: Write a little program that can compute the surface of circle, using the variables radius and pi=3.14159. The formula is of course radius, multiplied by radius, multiplied by pi. Print the outcome of your program as follows: 'The surface area of a circle with radius ... is: ...'.

In [ ]:
# circle code
  • Ex. 8: There is one operator (like the ones for multiplication and subtraction) that we did not mention yet, namely the modulus operator %. Could you figure by yourself what it does when you place it between two numbers (e.g. 113 % 9)? (PS: It's OK to get help online...) You don't need this operator all that often, but when you do, it comes in really handy!

In [ ]:
# try out the modulus operator!
  • Ex. 9: Can you use the modulus operator you just learned about to solve the following task? Write a code block that classifies a given amount of money into smaller monetary units. Set the amount variable to 11.56. You code should outputs a report listing the monetary equivalent in dollars, quarters, dimes, nickels, and pennies. Your program should report the maximum number of dollars, then the number of quarters, dimes, nickels, and pennies, in this order, to result in the minimum number of coins. Here are the steps in developing the program:

    Convert the amount (11.56) into cents (1156). Divide the cents by 100 to find the number of dollars, but first subtract the rest using the modulus operator! Divide the remaining cents by 25 to find the number of quarters, but, again, first subtract the rest using the modulus operator! Divide the remaining cents by 10 to find the number of dimes, etc. Divide the remaining cents by 5 to find the number of nickels, etc. The remaining cents are the pennies. Now display the result for your cashier!


In [ ]:
# cashier code

You've reached the end of Chapter 1! You can safely ignore the code block below -- it's only there to make the page prettier.


In [1]:
from IPython.core.display import HTML
def css_styling():
    styles = open("styles/custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[1]:

In [ ]: